//
//  MqInfoNewTableViewController.m
//  Meiqi
//
//  Created by 王郑 on 16/1/14.
//  Copyright © 2016年 KFC. All rights reserved.
//

#import "MqInfoNewTableViewController.h"
#import "MqInfoListModel.h"
#import "MqInfoListTableViewCell.h"
#import "MqInfoWebViewController.h"
@interface MqInfoNewTableViewController ()<SDCycleScrollViewDelegate>

// 数据源数组1
@property (strong, nonatomic) NSMutableArray *listArray;
// 数据源数组2
@property (strong, nonatomic) NSMutableArray *scrollArray;
// 展示轮播的view
@property (strong, nonatomic) UIView *myTableHeadView;
// 声明一个上拉加载的属性
@property (assign, nonatomic) NSInteger requestStart;

// FMDB里面的数据库,一个db就是一个数据库, 一个数据库里面可以放很多张表

@end

@implementation MqInfoNewTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    self.tableView.backgroundColor = [UIColor whiteColor];
#pragma mark ----- 数据源初始化
    _listArray = [NSMutableArray array];
    _scrollArray = [NSMutableArray array];
    _requestStart = 1;
#pragma mark ----- 关于tableView的
    // 注册cell
    [self.tableView registerClass:[MqInfoListTableViewCell class] forCellReuseIdentifier:@"NewCell"];
    self.tableView.rowHeight = 80 * kHeightBase;
    // 自定义表头
    _myTableHeadView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 200)];
    self.tableView.tableHeaderView = _myTableHeadView;
    
#pragma mark ----- 解析数据1
    [self setUpListData];
    
#pragma mark ----- 解析数据2
    [self setUpScrollData];
    
#pragma mark ----- 上拉加载
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        
        // 进入加载状态后会自动调用这个block
        // 修改请求的初始位置
        _requestStart += 1;
        
        [self setUpListData];
        
    }];
    
    
#pragma mark ----- 下拉刷新
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
       
        // 进入刷新状态
        _requestStart = 1;
        
        // 还要把数据源数组清空
        
        // 重新加载数据
        [self setUpListData];
    }];
    
#pragma mark ----- 关于数据库的操作
    
#pragma mark ----- 1.创建数据库
    // 先获取document路径,再拼接要保存的路径
        
#pragma mark ----- 3.创建表
    // 调用executeUpdate,这个方法的参数就是sql语句
    //[_db executeUpdate:@"create table IF NOT EXISTS InfoNewList (title text,newstime text,onclick text,titlePic text,ids text,classid text,picUrl text,uri text,topicDetailID text)"];
    
//    NSString *sql = @"create table IF NOT EXISTS InfoNewList (title text,newstime text,onclick text,titlePic text,ids text,classid text,picUrl text,uri text,topicDetailID text";
//    
//    //  建表
//    [[MqDatabase dataBaseHandle] buildListWithString:sql];
    
    
}

- (void)setUpListData
{
    [PKRequestManager requestWithUrlString:[NSString stringWithFormat:@"http://c.biketo.com/api/rss?classid=1&page=%ld&platform=1&pz=20&showType=newsList&time=0&version=1",(long)_requestStart] parDic:nil Method:GET finish:^(NSData *data) {
        
        NSMutableDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingAllowFragments) error:nil];

        
        NSArray *listAray = dic[@"list"];
        
#pragma mark ----- 4.先把数据库里的数据删除掉,这样每次只保存一次的数据
//        [[MqDatabase dataBaseHandle].db executeUpdate:@"delete from InfoNewList"];
        
        
#pragma mark ------ 下拉刷新的时候,把数据源数组清空,刷新只显示最前的20个数据
        if (_requestStart == 1) {
            
            [_listArray removeAllObjects];
            
        }
        
        for (NSMutableDictionary *oneDic in listAray) {
            
            MqInfoListModel *model = [[MqInfoListModel alloc] init];
            [model setValuesForKeysWithDictionary:oneDic];
            [_listArray addObject:model];
            
#pragma mark ----- 5.往表里插入数据
            
            // FMDB插入的时候必须是一个对象,如果表里面的一个字段是int类型的,插入的时候需要插入一个NSNumber对象
            [[MqDatabase dataBaseHandle].db executeUpdate:@"insert into InfoNewList (title,newstime,onclick,titlePic,ids,classid,picUrl,uri,topicDetailID) values(?,?,?,?,?,?,?,?,?)",model.title,model.newstime,model.onclick,model.titlePic,model.ids,model.classid,model.picUrl,model.uri,model.topicDetailID];
        }
#pragma mark ------ 结束刷新
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        // 刷新数据
        [self.tableView reloadData];
        
    } error:^(NSError *error) {

//        NSLog(@"网络请求失败");
#pragma mark ----- 4.先把之前数据库里的表的数据 取出来 存进 数据源数组里
        // 执行查找的操作,调用的方法是executeQuery,参数是sql的查找语句,会返回一个FMResultSet类型的结果
        FMResultSet *result = [[MqDatabase dataBaseHandle].db executeQuery:@"select * from InfoNewList"];
        
        while ([result next]) {
            
            NSString *title = [result stringForColumn:@"title"];
            NSString *newstime = [result stringForColumn:@"newstime"];
            NSString *onclick = [result stringForColumn:@"onclick"];
            NSString *titlePic = [result stringForColumn:@"titlePic"];
            NSString *ids = [result stringForColumn:@"ids"];
            NSString *classid = [result stringForColumn:@"classid"];
            NSString *picUrl = [result stringForColumn:@"picUrl"];
            NSString *uri = [result stringForColumn:@"uri"];
            NSString *topicDetailID = [result stringForColumn:@"topicDetailID"];
            
            MqInfoListModel *model = [[MqInfoListModel alloc] init];
            model.title = title;
            model.newstime = newstime;
            model.onclick = onclick;
            model.titlePic = titlePic;
            model.ids = ids;
            model.classid = classid;
            model.picUrl = picUrl;
            model.uri = uri;
            model.topicDetailID = topicDetailID;
            [_listArray addObject:model];
            
        }

    } path:@"newListData"];
    
}

- (void)setUpScrollData
{
    [PKRequestManager requestWithUrlString:@"http://c.biketo.com/api/hb?platform=1&showType=slideList&time=1452511286&version=1" parDic:nil Method:GET finish:^(NSData *data) {
        
        NSMutableDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
        
        NSArray *list = dic[@"list"];
        for (NSMutableDictionary *oneDic in list) {
            
            if (![oneDic[@"hb"] isEqualToString:@""]) {
                
                MqInfoListModel *model = [[MqInfoListModel alloc] init];
                [model setValuesForKeysWithDictionary:oneDic];
                [_scrollArray addObject:model];
            }
            
    }
        
        // 创建一个数组来保存图片的地址
        NSMutableArray *picArray = [NSMutableArray array];
        for (int i = 0; i < _scrollArray.count; i++) {
            
            MqInfoListModel *model = _scrollArray[i];
            [picArray addObject:model.picUrl];
            
        }
        // 创建一个第三方轮播
        SDCycleScrollView *headScrollView = [SDCycleScrollView cycleScrollViewWithFrame:_myTableHeadView.frame imageURLStringsGroup:picArray];
        headScrollView.placeholderImage = [UIImage imageNamed:@"infoplaceholder"];
        headScrollView.delegate = self;
        [_myTableHeadView addSubview:headScrollView];

    } error:^(NSError *error) {
//        NSLog(@"%@",error);
        
    } path:@"newScrollData"];
}
#pragma mark ---- 实现第三方的轮播的代理方法
- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index
{
    
#pragma mark --- 传ids,拼接网页
    MqInfoListModel *model = _scrollArray[index];
    NSString *ids = model.ids;
    NSString *classID = model.classid;
    // 创建通知,让主页面去跳转
    NSDictionary *dic = @{
                           @"ids" : ids,
                           @"classID" : classID
                        };
    [[NSNotificationCenter defaultCenter] postNotificationName:@"push" object:self userInfo:dic];

    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}




- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return _listArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    MqInfoListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"NewCell" forIndexPath:indexPath];
    
   
    // 展示数据
    MqInfoListModel *model = _listArray[indexPath.row];
    cell.model = model;
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{

#pragma mark --- 传ids,拼接网页
    MqInfoListModel *model = _listArray[indexPath.row];
    NSString *ids = model.ids;
    NSString *classID = model.classid;
     // 创建通知,让主页面去跳转
    NSDictionary *dic = @{
                          @"ids" : ids,
                          @"classID" : classID
                          };

     [[NSNotificationCenter defaultCenter] postNotificationName:@"push" object:self userInfo:dic];
    
    
    
}

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
 
    CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"transform.rotation"];
    
    // 添加到数组里 (变值 为角度)
    animation.values = @[@(-M_PI_4 /90.0 * 15),@(M_PI_4 /90.0 * 15),@(-M_PI_4 /90.0 * 15)];
    
    animation.duration = 0.4;
    animation.repeatCount = 1;
    
    // 把动画添加到处layer蹭上
    [cell.layer addAnimation:animation forKey:@"transform.rotation"];
    
}



/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
